package com.wms.service.Impl;

import com.wms.entity.*;
import com.wms.mapper.*;
import com.wms.service.MenuService;
import com.wms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public WmsMenu findById(long menuId) {
        WmsMenu menu = menuMapper.findById(menuId);
        return menu;
    }



    public List<WmsMenu> findAll(String name) {
        //根据用户名查询用户
        WmsUser user = userMapper.findByUserName(name);
        //根据用户查询角色
        List<WmsUserRole> userRoles = userRoleMapper.findRoleIdByUser(user);
        List<WmsMenu> menus = new ArrayList<>();
        List<WmsRoleMenu> roleMenus = new ArrayList<>();
        for (WmsUserRole userRole : userRoles) {
            //根据角色查询菜单
            WmsRole role = roleMapper.findRoleIdById(userRole.getRoleId());
            roleMenus = roleMenuMapper.findAllByRole(role);
            for (WmsRoleMenu roleMenu : roleMenus) {
                WmsMenu menu = menuMapper.findById(roleMenu.getMenuId());
                menus.add(menu);
            }
        }
        for (WmsMenu menu : menus) {
            if (menu != null && menu.getMenuType().equals("M")){
                menu.setChildren(menuMapper.findByPid(menu.getMenuId(),roleMenus));
            }
        }
        menus.removeIf(menu -> menu.getParentId() != 0);
        return menus;
    }
}


